<?php

declare(strict_types=1);

namespace Tools\Net;

/**
 * Class Upload
 *
 * @package Tools\Net
 */
class Upload
{
    /**
     * Upload files, in the form of a binary file stream.
     *
     * @param $url
     * @param $params
     * @param $filePath
     * @param $headers
     *
     * @static
     *
     * @return bool|string
     */
    public static function binary($url, $params, $filePath, $headers) : mixed
    {
        $curlHTTP = curl_init();

        $url = "{$url}?" . http_build_query($params); // build url

        curl_setopt($curlHTTP, CURLOPT_URL, $url);
        curl_setopt($curlHTTP, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curlHTTP, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($curlHTTP, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curlHTTP, CURLOPT_TIMEOUT, 60);

        $fileData = '';

        if ($filePath) { // set upload file
            $file = fopen($filePath, 'r');

            $fileData = fread($file, filesize($filePath));

            fclose($file);
        }

        curl_setopt($curlHTTP, CURLOPT_POSTFIELDS, $fileData);

        $result = curl_exec($curlHTTP);

        curl_close($curlHTTP);

        return $result;
    }

    /**
     * Upload file non-binary file stream.
     *
     * @param $url
     * @param array $params
     * @param bool $uploadFile
     *
     * @static
     * 
     * @return bool|string
     */
    public static function notBinary($url, $params = [], $uploadFile = false) : mixed
    {
        $curlHTTP = curl_init();

        curl_setopt($curlHTTP, CURLOPT_URL, $url);
        curl_setopt($curlHTTP, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curlHTTP, CURLOPT_CUSTOMREQUEST, 'POST');

        if ($uploadFile) { // set upload file
            $file = new \CURLFile ($uploadFile['file'], $uploadFile['type'], $uploadFile['name']);
            $params ['file'] = $file;
        }

        curl_setopt($curlHTTP, CURLOPT_POSTFIELDS, $params);

        $result = curl_exec($curlHTTP);

        curl_close($curlHTTP);

        return $result;
    }
}